<?php

namespace app\common\logic;

use app\common\library\exception\ApiException;
use app\common\library\MemberVo;
use app\common\model\Coupon;
use app\common\model\CouponSetting;
use think\db\Query;

class CouponLogic extends BaseLogic
{
    public $model;

    public function assignModel()
    {
        $this->model          = new Coupon();
    }
    public function handleSearch(Query $query, array $params): Query
    {
        if (isset($params['list_type']) && !empty($params['list_type'])){
            if ($params['list_type'] == 1){
                $query->where('coupon.end_time','EGT',time());
                $query->where('coupon.status',1);//未使用
            }elseif ($params['list_type'] == 2){
                $whereOrRaw = "coupon.end_time  < ".time()." or coupon.status  = 2";
                $query->whereOrRaw($whereOrRaw);
            }
        }
        if (isset($params['member_id']) && !empty($params['member_id'])){
            $query->where('coupon.member_id',$params['member_id']);
        }
        return $query;
    }

    /**
     * 车主端 优惠券列表
     * @return mixed
     */
    public function index($params)
    {
        $params['member_id'] = MemberVo::instance()->getMemberId();
        $params['list_type'] = 1;// 1优惠券列表 2历史优惠券
        $params['with'] = ['couponSetting'];
        $params['field'] = "id,money,least_cost,begin_time,end_time";
        $list = $this->getPageList($params)->each(function (&$item){
            $item['name'] = htmlspecialchars_decode($item['coupon_setting']['name']);
            $item['begin_time'] = date('Y.m.d', $item['begin_time']);
            $item['end_time'] = date('Y.m.d', $item['end_time']);
            $item['least_cost'] = htmlspecialchars_decode($item['least_cost']);
            $item['desc'] = $item['least_cost'] == 0 ? "无门槛" : "满{$item['least_cost']}元可用";
            unset($item['coupon_setting']);
            return $item;
        });
        return $list;
    }

    /**
     * 车主端 历史优惠券列表
     * @return mixed
     */
    public function history($params)
    {
        $params['member_id'] = MemberVo::instance()->getMemberId();
        $params['list_type'] = 2;// 1优惠券列表 2历史优惠券
        $params['with'] = ['couponSetting'];
        $params['field'] = "id,money,least_cost,begin_time,end_time,status";
        $list = $this->getPageList($params)->each(function (&$item){
            $item['name'] = htmlspecialchars_decode($item['coupon_setting']['name']);
            $item['begin_time'] = date('Y.m.d', $item['begin_time']);
            $item['end_time'] = date('Y.m.d', $item['end_time']);
            if ($item['status'] == 1){
                $item['history_type'] = 1; //已过期
            }else{
                $item['history_type'] = 2; //已使用
            }
            $item['least_cost'] = htmlspecialchars_decode($item['least_cost']);
            $item['desc'] = $item['least_cost'] == 0 ? "无门槛" : "满{$item['least_cost']}元可用";
            unset($item['coupon_setting'],$item['status']);
            return $item;
        });
        return $list;
    }

    /**
     * 领取优惠券
     * @param $params
     * @return bool
     * @throws ApiException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function get_coupon($params)
    {
        $coupon_info = CouponSetting::get($params['id']);
        if (!$coupon_info)
            throw new ApiException('优惠券信息不存在',404);
        if($coupon_info['status'] == 2)
            throw new ApiException('该优惠券已经暂停领取',404);
        if ($coupon_info['get_begin_time'] > time() || $coupon_info['get_end_time'] < time())
            throw new ApiException('不在领取的时间范围',404);
        if ($coupon_info['coupon_nums'] < 1)
            throw new ApiException('该优惠券已被领取完了',404);
        if ($coupon_info['rule'] == 2){//生日券
            if (!CouponSetting::checkCurrentAllowGetBrithdayCouponByMemberId(MemberVo::instance()->getMemberId())){
                throw new ApiException('未达到领取条件',404);
            }
        }else{
            $num = Coupon::where(['member_id'=>MemberVo::instance()->getMemberId(),'setting_id'=>$params['id']])->count('id');
            if ($coupon_info['get_limit'] <= $num)
                throw new ApiException('超过可领取的数量',404);
        }
        if ($coupon_info['date_type'] == 1){
            $begin_time = strtotime($coupon_info['use_begin_time']);
            $end_time = strtotime($coupon_info['use_end_time']);
        }elseif ($coupon_info['date_type'] == 2){
            $begin_time = time();
            if ($coupon_info['fixed_day'] == 1){
                $end_time = strtotime(date("Y-m-d 23:59:59"));
            }else{
                $days = $coupon_info['fixed_day'] -1;
                $end_time = strtotime(date("Y-m-d 23:59:59",strtotime("+".$days." day")));
            }
        }
        Coupon::create([
            'member_id'=>MemberVo::instance()->getMemberId(),
            'money'=>$coupon_info['money'],
            'type'=>$coupon_info['type'],
            'least_cost'=>$coupon_info['least_cost'],
            'begin_time'=>$begin_time,
            'end_time'=>$end_time,
            'setting_id'=>$coupon_info['id'],
            'status'=>1
        ]);
        return true;
    }




}